<template>
  <div class="home-page">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card class="welcome-card">
          <h1>欢迎使用房价分析系统</h1>
          <p>本系统提供全面的房价数据分析、可视化和趋势预测功能，帮助您更好地了解房地产市场</p>
        </a-card>
      </a-col>
    </a-row>

    <!-- 数据概览 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="5">
        <a-card>
          <a-statistic
            title="收录城市"
            :value="statistics.cityCount"
            :loading="loading"
          >
            <template #suffix>
              <apartment-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="5">
        <a-card>
          <a-statistic
            title="房源总数"
            :value="statistics.houseCount"
            :loading="loading"
          >
            <template #suffix>
              <home-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="5">
        <a-card>
          <a-statistic
            title="平均价格"
            :value="statistics.avgPrice"
            :precision="2"
            :loading="loading"
            suffix="万元"
          >
            <template #prefix>
              <money-collect-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="4.5">
        <a-card>
          <a-statistic
            title="最低价格"
            :value="statistics.minPrice"
            :precision="2"
            :loading="loading"
            suffix="万元"
          >
            <template #prefix>
              <fall-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="4.5">
        <a-card>
          <a-statistic
            title="最高价格"
            :value="statistics.maxPrice"
            :precision="2"
            :loading="loading"
            suffix="万元"
          >
            <template #prefix>
              <rise-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 热门城市 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="24">
        <a-card title="热门城市房价" :bordered="false">
          <a-row :gutter="16">
            <a-col :span="18">
              <div ref="cityPriceChartRef" style="width: 100%; height: 300px"></div>
            </a-col>
            <a-col :span="6">
              <div class="hot-cities">
                <h3>热门城市</h3>
                <a-list :loading="loading">
                  <a-list-item v-for="city in hotCities" :key="city.name">
                    <a-list-item-meta>
                      <template #title>
                        <a @click="navigateToCityAnalysis(city.name)">{{ city.name }}</a>
                      </template>
                      <template #description>
                        均价: {{ city.avgUnitPrice }} 万元/㎡
                      </template>
                    </a-list-item-meta>
                    <template #extra>
                      <a-tag :color="city.trend === 'up' ? 'red' : 'green'">
                        {{ city.trend === 'up' ? '↑' : '↓' }} {{ city.changeRate }}%
                      </a-tag>
                    </template>
                  </a-list-item>
                </a-list>
              </div>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>

    <!-- 功能导航 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="6">
        <a-card hoverable @click="$router.push('/search')">
          <template #cover>
            <div class="feature-icon">
              <search-outlined />
            </div>
          </template>
          <a-card-meta title="房源搜索">
            <template #description>
              <p>多条件筛选，精准定位您的理想房源</p>
            </template>
          </a-card-meta>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card hoverable @click="$router.push('/analysis')">
          <template #cover>
            <div class="feature-icon">
              <bar-chart-outlined />
            </div>
          </template>
          <a-card-meta title="房价分析">
            <template #description>
              <p>多维度分析房价数据，了解市场走势</p>
            </template>
          </a-card-meta>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card hoverable @click="$router.push('/city-comparison')">
          <template #cover>
            <div class="feature-icon">
              <apartment-outlined />
            </div>
          </template>
          <a-card-meta title="城市对比">
            <template #description>
              <p>多城市房价数据对比，全面了解区域差异</p>
            </template>
          </a-card-meta>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card hoverable>
          <template #cover>
            <div class="feature-icon">
              <info-circle-outlined />
            </div>
          </template>
          <a-card-meta title="关于系统">
            <template #description>
              <p>了解房价分析系统的数据来源与功能说明</p>
            </template>
          </a-card-meta>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useHouseStore } from '../stores/houseStore'
import { useAnalysisStore } from '../stores/analysisStore'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  HomeOutlined,
  ApartmentOutlined,
  MoneyCollectOutlined,
  RiseOutlined,
  FallOutlined,
  SearchOutlined,
  BarChartOutlined,
  LineChartOutlined,
  ClusterOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const houseStore = useHouseStore()
const analysisStore = useAnalysisStore()

// 状态
const loading = ref(false)
const statistics = ref({
  cityCount: 0,
  houseCount: 0,
  avgPrice: 0,
  avgUnitPrice: 0,
  minPrice: 0,
  maxPrice: 0
})
const hotCities = ref([])

// 图表引用
const cityPriceChartRef = ref(null)
let cityPriceChart = null

// 获取首页数据
const fetchHomeData = async () => {
  loading.value = true
  
  try {
    // 获取城市列表
    const cities = await houseStore.fetchCities()
    statistics.value.cityCount = cities.length
    
    // 获取系统统计数据
    const systemStats = await analysisStore.fetchSystemStatistics()
    statistics.value.houseCount = systemStats.totalHouses
    statistics.value.avgPrice = systemStats.avgPrice
    statistics.value.avgUnitPrice = systemStats.avgPrice
    statistics.value.maxPrice = systemStats.maxPrice
    statistics.value.minPrice = systemStats.minPrice
    // 获取热门城市数据
    const cityStats = await analysisStore.fetchHotCityStatistics()
    hotCities.value = cityStats.map(city => ({
      name: city.city,
      avgUnitPrice: city.avgUnitPrice ? city.avgUnitPrice.toFixed(2) : '0.00',
      trend: city.priceChange >= 0 ? 'up' : 'down',
      changeRate: city.priceChange ? Math.abs(city.priceChange).toFixed(2) : '0.00'
    }))
    
    // 更新图表
    nextTick(() => {
      initCityPriceChart(cityStats)
    })
  } catch (error) {
    console.error('获取首页数据失败:', error)
    message.error('获取首页数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化城市房价图表
const initCityPriceChart = (cityStats) => {
  if (!cityPriceChartRef.value) return
  
  cityPriceChart = echarts.init(cityPriceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['平均总价', '平均单价']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: cityStats.map(item => item.city)
    },
    yAxis: [
      {
        type: 'value',
        name: '总价(万元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '单价(万元/㎡)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '平均总价',
        type: 'bar',
        data: cityStats.map(item => item.avgPrice),
        yAxisIndex: 0,
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '平均单价',
        type: 'line',
        data: cityStats.map(item => item.avgUnitPrice),
        yAxisIndex: 1,
        smooth: true,
        lineStyle: {
          color: '#fa8c16'
        },
        itemStyle: {
          color: '#fa8c16'
        }
      }
    ]
  }
  
  cityPriceChart.setOption(option)
}

// 导航到城市分析页面
const navigateToCityAnalysis = (city) => {
  router.push({
    path: '/analysis',
    query: { city }
  })
}

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  cityPriceChart?.resize()
})

// 页面加载时获取数据
onMounted(() => {
  fetchHomeData()
})
</script>

<style scoped lang="scss">
.home-page {
  padding: 24px;
  
  .welcome-card {
    text-align: center;
    padding: 20px 0;
    
    h1 {
      font-size: 28px;
      color: #1890ff;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 16px;
      color: #666;
    }
  }
  
  .feature-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 120px;
    font-size: 48px;
    background-color: #f5f7fa;
    color: #1890ff;
  }
  
  .hot-cities {
    h3 {
      margin-bottom: 16px;
      font-size: 16px;
      color: #666;
    }
  }
}
</style> 